package com.ars.common.servlet;

import com.ars.common.beans.Active.Active;
import com.ars.common.beans.User.User;
import com.ars.common.dao.addActiveMysql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addActiveServlet")
public class addActiveServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为UTF-8，避免中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("addActiveServlet");

        // 获取表单参数
        String activeName = request.getParameter("activeName");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String userName = request.getParameter("Username");
        String userID = request.getParameter("UserID");
        String activeType = request.getParameter("ActiveType");

        // 创建Active对象并设置属性
        Active active = new Active();
        active.setName(activeName);
        active.setBeginTime(beginTime);
        active.setEndTime(endTime);
        active.setCreator(userName);
        active.setCreatorID(userID);
        active.setType(activeType);

        // 获取Session中登录者信息
        User loginUser = (User) request.getSession().getAttribute("LogUser");
        if (loginUser != null) {
            active.setCreator(loginUser.getName());
            active.setCreatorID(loginUser.getUserID());
        }

        // 将活动信息插入数据库
        try {
            addActiveMysql.addActive(active);
            System.out.println("添加活动成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 重定向到活动发布页面
        String url = request.getContextPath() + "/PublicationActive";
        response.sendRedirect(url);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
